<template>
    <div class="stats-container">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item>客户统计</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="filter-container">
            <el-input v-model="searchStaffName" style="width: 200px" placeholder="搜索接待人员" clearable
                @clear="handleClearSearch" @keyup.enter="handleSearch">
                <template #prefix>
                    <el-icon class="el-input__icon">
                        <search />
                    </el-icon>
                </template>
            </el-input>

            <el-radio-group v-model="dateRangeType" @change="handleDateRangeChange" style="margin: 0 10px">
                <el-radio value="day">日</el-radio>
                <el-radio value="month">月</el-radio>
            </el-radio-group>

            <el-date-picker v-if="dateRangeType === 'day'" v-model="selectedDate" type="date"
                :placeholder="datePlaceholder" value-format="YYYY-MM-DD" style="width: 200px" :clearable="true"
                @change="handleDateChange">
                <template #suffix-icon>
                    <el-icon>
                        <calendar />
                    </el-icon>
                </template>
            </el-date-picker>

            <el-date-picker v-else v-model="selectedDate" type="month" :placeholder="datePlaceholder"
                value-format="YYYY-MM" style="width: 200px" :clearable="true" @change="handleDateChange">
                <template #default="cell">
                    <div class="el-date-table-cell" :class="{ current: cell.isCurrent }">
                        <span class="el-date-table-cell__text">{{ cell.text + 1 }}月</span>
                    </div>
                </template>
                <template #suffix-icon>
                    <el-icon>
                        <calendar />
                    </el-icon>
                </template>
            </el-date-picker>

            <div style="margin-left: auto">
                <el-button type="primary" plain @click="handleImport" @mouseover="isHover = true"
                    @mouseleave="isHover = false">
                    <img :src="isHover ? whiteIcon : normalIcon" class="custom-icon" />
                    <span>导入</span>
                </el-button>
                <el-button type="primary" :icon="Plus" @click="handleAdd">
                    新建
                </el-button>
            </div>
        </div>

        <el-alert v-if="error" :title="error" type="error" show-icon class="mb-20" />
        <el-skeleton v-if="loading" :rows="6" animated />

        <el-table v-else :data="tableData" style="width: 100%" height="calc(100vh - 250px)" :fit="true"
            v-loading="loading">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="staffName" label="接单人员" width="150" show-overflow-tooltip />
            <el-table-column prop="consultCustomerCount" label="咨询客户数" width="120" />
            <el-table-column v-if="dateRangeType === 'day'" prop="manualReplyRate" label="人工回复率" width="120" />
            <el-table-column v-if="dateRangeType === 'day'" prop="avgFirstResponseTime" label="平均首次响应时间" width="150" />
            <el-table-column prop="addedCustomerCount" label="添加专员的客户数" width="150" />
            <el-table-column prop="notAddedCustomerCount" label="未添加客户数" width="120" />
            <el-table-column prop="customerAddRate" label="客户添加率" width="120">
                <template #default="scope">
                    {{ (scope.row.customerAddRate * 100).toFixed(0) }}%
                </template>
            </el-table-column>
            <el-table-column prop="wecomAddCount" label="留企业微信添加数" width="150" />
            <el-table-column v-if="dateRangeType === 'day'" prop="recordDate" label="日期" width="120" />
            <el-table-column prop="qqGroupData" label="QQ群数据" width="120" show-overflow-tooltip />
            <el-table-column prop="wechatData" label="微信群数据" width="120" show-overflow-tooltip />
            <el-table-column prop="accurateData" label="精准数据" width="150" show-overflow-tooltip />
            <el-table-column fixed="right" label="操作" min-width="120" v-if="dateRangeType === 'day'">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="editRow(scope.row)">
                        编辑
                    </el-button>
                    <el-button link type="danger" size="small" @click="deleteRow(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" size="small" layout="prev, pager, next" :total="pagination.total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination-container" />

        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%" :close-on-click-modal="false">
            <el-form :model="form" label-width="120px" :rules="rules" ref="formRef" label-position="top">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item :label="dateRangeType === 'day' ? '日期' : '月份'" prop="recordDate"
                            class="form-item-top">
                            <el-date-picker v-model="form.recordDate" :type="dateRangeType === 'day' ? 'date' : 'month'"
                                :placeholder="dateRangeType === 'day' ? '选择日期' : '选择月份'"
                                :value-format="dateRangeType === 'day' ? 'YYYY-MM-DD' : 'YYYY-MM'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="接待人员" prop="staffName" class="form-item-top">
                            <el-input v-model="form.staffName" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="咨询客户数" prop="consultCustomerCount" class="form-item-top">
                            <el-input v-model="form.consultCustomerCount" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="添加专员的客户数" prop="addedCustomerCount" class="form-item-top">
                            <el-input v-model="form.addedCustomerCount" type="number" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="留企业微信添加数" prop="wecomAddCount" class="form-item-top">
                            <el-input v-model="form.wecomAddCount" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="精准数据" prop="accurateData" class="form-item-top">
                            <el-input v-model="form.accurateData" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="QQ群数据" prop="qqGroupData" class="form-item-top">
                            <el-input v-model="form.qqGroupData" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="微信群数据" prop="wechatData" class="form-item-top">
                            <el-input v-model="form.wechatData" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="备注" prop="accurateData" class="form-item-top">
                            <el-input v-model="form.accurateData" type="textarea" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog v-model="importDialogVisible" title="导入" width="60%" style="height: 520px;">
            <div class="upload-container">
                <div v-if="!importFile" style="height: 100%;display: flex;flex-direction: column;">
                    <div class="date-picker-container">
                        <el-date-picker v-model="importDate" :type="dateRangeType === 'day' ? 'date' : 'month'"
                            :placeholder="dateRangeType === 'day' ? '选择导入日期' : '选择导入月份'"
                            :value-format="dateRangeType === 'day' ? 'YYYY-MM-DD' : 'YYYY-MM'" />
                    </div>

                    <el-upload ref="uploadRef" class="upload-demo" drag action="#" :auto-upload="false"
                        :on-change="handleFileChange" :show-file-list="false" accept=".xlsx,.xls,.csv" @click.stop>
                        <div class="el-upload__text">
                            点击上传或将表格拖拽到此处
                        </div>
                    </el-upload>
                </div>

                <div class="selected-file" v-else>
                    <el-icon>
                        <document />
                    </el-icon>
                    <span>{{ importFile.name }}</span>
                    <el-icon class="close-icon" @click="importFile = null">
                        <close />
                    </el-icon>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer" style="display: flex; justify-content: flex-start;">
                    <el-button v-if="importFile" @click="submitImport" :loading="importLoading">
                        上传表格
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import normalIcon from '../../../assets/import-icon.svg'
import whiteIcon from '../../../assets/import-icon-white.svg'
import { Search, Calendar, Plus, Document, Close } from '@element-plus/icons-vue'
import { getStatsList, addStatsData, updateStatsData, deleteStatsData, importStatsData, getMonthlyCollectData } from '../../../api/media/stats'
import { ElMessage, ElMessageBox } from 'element-plus'

const isHover = ref(false)

const todayDate = computed(() => {
    const date = new Date()
    return date.toISOString().split('T')[0]
})

const currentMonth = computed(() => {
    const date = new Date()
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
})

const datePlaceholder = computed(() => {
    return dateRangeType.value === 'day' ? todayDate.value : currentMonth.value
})

const searchStaffName = ref('')
const selectedDate = ref('')
const loading = ref(false)
const error = ref(null)
const dateRangeType = ref('day')

const pagination = ref({
    pageNum: 1,
    pageSize: 20,
    total: 0
})

const tableData = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('新增统计')
const form = ref({
    staffName: '',
    consultCustomerCount: 0,
    manualReplyRate: '100%',
    avgFirstResponseTime: '<1分钟',
    addedCustomerCount: 0,
    notAddedCustomerCount: 0,
    wecomAddCount: 0,
    accurateData: '',
    recordDate: ''
})
const formRef = ref(null)
const currentEditId = ref(null)

const importDialogVisible = ref(false)
const importFile = ref(null)
const importLoading = ref(false)
const importDate = ref('')

const rules = {
    recordDate: [{ required: true, message: '请选择日期', trigger: 'change' }],
    staffName: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
    consultCustomerCount: [{ required: true, message: '请输入咨询客户数', trigger: 'blur' }],
    manualReplyRate: [{ required: true, message: '请输入人工回复率', trigger: 'blur' }],
    avgFirstResponseTime: [{ required: true, message: '请输入平均首次响应时间', trigger: 'blur' }]
}

const formatDate = (date) => {
    if (!date) return ''
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

const formatMonth = (date) => {
    if (!date) return ''
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    return `${year}-${month}`
}

const fetchStats = async () => {
    loading.value = true
    error.value = null
    try {
        const params = {
            pageNum: pagination.value.pageNum,
            pageSize: pagination.value.pageSize,
            ...(searchStaffName.value && { staffName: searchStaffName.value }),
            recordDate: selectedDate.value
        }

        let res
        if (dateRangeType.value === 'day') {
            res = await getStatsList(params)
        } else {
            res = await getMonthlyCollectData(params)
        }

        tableData.value = res.rows.map((item) => ({
            id: item.id,
            staffName: item.staffName,
            consultCustomerCount: item.consultCustomerCount,
            manualReplyRate: item.manualReplyRate,
            avgFirstResponseTime: item.avgFirstResponseTime,
            addedCustomerCount: item.addedCustomerCount,
            notAddedCustomerCount: item.notAddedCustomerCount,
            customerAddRate: item.customerAddRate,
            wecomAddCount: item.wecomAddCount,
            accurateData: item.accurateData,
            recordDate: dateRangeType.value === 'day'
                ? formatDate(item.recordDate)
                : formatMonth(item.recordDate),
            qqGroupData: item.qqGroupData,
            wechatData: item.wechatData
        }))

        pagination.value.total = res.total
    } catch (err) {
        error.value = `请求失败: ${err.response?.data?.message || err.message}`
        console.error('获取统计列表失败:', err)
    } finally {
        loading.value = false
    }
}

const handleDateRangeChange = () => {
    if (dateRangeType.value === 'month') {
        if (!selectedDate.value) {
            selectedDate.value = currentMonth.value
        } else {
            const [year, month] = selectedDate.value.split('-')
            selectedDate.value = `${year}-${month}`
        }
    } else {
        selectedDate.value = ''
    }
    fetchStats()
}

const handleSearch = () => {
    pagination.value.pageNum = 1
    fetchStats()
}

const handleSizeChange = (val) => {
    pagination.value.pageSize = val
    fetchStats()
}

const handleCurrentChange = (val) => {
    pagination.value.pageNum = val
    fetchStats()
}

const handleClearSearch = () => {
    searchStaffName.value = ''
    handleSearch()
}

const handleDateChange = () => {
    handleSearch()
}

const handleImport = () => {
    importDialogVisible.value = true
    importFile.value = null
    importDate.value = selectedDate.value || (dateRangeType.value === 'day' ? formatDate(new Date()) : formatMonth(new Date()))
}

const handleFileChange = (file) => {
    importFile.value = file.raw
}

const uploadRef = ref(null)

const submitImport = async () => {
    if (!importFile.value) {
        ElMessage.warning('请先选择文件')
        return
    }

    try {
        importLoading.value = true
        const formData = new FormData()
        formData.append('file', importFile.value)

        const params = {}
        if (importDate.value) {
            params.recordDate = importDate.value
        }

        await importStatsData(formData, params)
        ElMessage.success('导入成功')

        if (uploadRef.value) {
            uploadRef.value.clearFiles()
            const uploadInput = uploadRef.value.$el.querySelector('input[type="file"]')
            if (uploadInput) {
                uploadInput.value = ''
            }
        }
        importFile.value = null
        importDialogVisible.value = false
        fetchStats()
    } catch (err) {
        let errorMessage = '导入失败'
        if (err.response) {
            errorMessage += `: ${err.response.data.message || err.response.statusText}`
        } else {
            errorMessage += `: ${err.message || '未知错误'}`
        }
        ElMessage.error(errorMessage)
        console.error('导入失败:', err)
    } finally {
        importLoading.value = false
    }
}

const editRow = (row) => {
    dialogTitle.value = '编辑统计'
    currentEditId.value = row.id
    form.value = {
        staffName: row.staffName,
        consultCustomerCount: row.consultCustomerCount,
        manualReplyRate: row.manualReplyRate,
        avgFirstResponseTime: row.avgFirstResponseTime,
        addedCustomerCount: row.addedCustomerCount,
        notAddedCustomerCount: row.notAddedCustomerCount,
        wecomAddCount: row.wecomAddCount,
        accurateData: row.accurateData,
        recordDate: row.recordDate
    }
    dialogVisible.value = true
}

const deleteRow = async (row) => {
    try {
        await ElMessageBox.confirm('删除后不能恢复, 请确认是否删除。', '确认删除', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        await deleteStatsData(row.id)
        ElMessage.success('删除成功')
        fetchStats()
    } catch (err) {
        if (err !== 'cancel') {
            ElMessage.error('删除失败: ' + (err.message || '未知错误'))
            console.error('删除失败:', err)
        }
    }
}

const handleAdd = () => {
    dialogTitle.value = '新增统计'
    currentEditId.value = null
    form.value = {
        staffName: '',
        consultCustomerCount: 0,
        manualReplyRate: '100%',
        avgFirstResponseTime: '<1分钟',
        addedCustomerCount: 0,
        notAddedCustomerCount: 0,
        wecomAddCount: 0,
        qqGroupData: null,
        wechatData: null,
        accurateData: '',
        recordDate: dateRangeType.value === 'day' ? formatDate(new Date()) : formatMonth(new Date())
    }
    dialogVisible.value = true
}

const submitForm = async () => {
    try {
        await formRef.value.validate()

        const params = {
            staffName: form.value.staffName,
            consultCustomerCount: form.value.consultCustomerCount,
            manualReplyRate: form.value.manualReplyRate,
            avgFirstResponseTime: form.value.avgFirstResponseTime,
            addedCustomerCount: form.value.addedCustomerCount,
            notAddedCustomerCount: form.value.notAddedCustomerCount,
            wecomAddCount: form.value.wecomAddCount,
            accurateData: form.value.accurateData,
            recordDate: form.value.recordDate
        }

        if (currentEditId.value) {
            await updateStatsData({ ...params, id: currentEditId.value })
            ElMessage.success('编辑成功')
        } else {
            await addStatsData(params)
            ElMessage.success('新增成功')
        }

        dialogVisible.value = false
        fetchStats()
    } catch (err) {
        if (!err.message) {
            return
        }
        ElMessage.error('操作失败: ' + (err.message || '未知错误'))
        console.error('操作失败:', err)
    }
}

onMounted(() => {
    fetchStats()
})
</script>

<style scoped>
.form-item-top {
    margin-top: 16px;
}

.header {
    margin-bottom: 5px;
    padding: 15px 0;
    font-size: 20px;
}

.title {
    font-size: 20px;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 16px 0;
}

.stats-container {
    width: 100%;
    overflow-x: auto;
    box-sizing: border-box;
}

.filter-container {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
    flex-wrap: wrap;
    align-items: center;
}

.pagination-container {
    margin-top: 20px;
    justify-content: flex-end;
}


.custom-icon {
    width: 16px;
    height: 16px;
    margin-right: 6px;
}

.upload-container {
    height: 380px;
    text-align: center;
    box-sizing: border-box;
}

.upload-demo {
    width: 100%;
    flex: 1;
}

:deep(.el-upload.is-drag) {
    height: 100%;
}

:deep(.el-upload-dragger) {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.el-upload__text {
    margin: 10px 0;
    color: #666;
}

.selected-file {
    margin-top: 15px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.selected-file span {
    margin-left: 10px;
    flex-grow: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.close-icon {
    cursor: pointer;
    color: #999;
}

.close-icon:hover {
    color: #666;
}

.date-picker-container {
    margin-bottom: 20px;
    text-align: left;
}

@media (max-width: 768px) {
    .el-table {
        font-size: 12px;
    }

    .el-button {
        padding: 5px;
        font-size: 12px;
    }

    .el-table-column {
        width: auto !important;
    }

    .filter-container {
        flex-direction: column;
        align-items: flex-start;
    }
}
</style>